import { cookies } from "next/headers";
import { NextResponse } from "next/server";

/** Server-side proxy to Core API /auth/token. Stores JWT in a httpOnly cookie. */
export async function POST() {
  const coreApi = process.env.EUGENE_CORE_API_URL ?? "http://eugene_ws:8000";
  const res = await fetch(`${coreApi}/auth/token`, {
    method: "POST",
    cache: "no-store",
  });
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    return NextResponse.json(
      { error: `core-api token issue failed: ${res.status} ${text}` },
      { status: res.status }
    );
  }
  const data = (await res.json()) as { access_token: string; expires_in: number };
  const store = await cookies();
  // `secure` MUST be opt-in: browsers reject Secure cookies on http://localhost.
  // Only enable when explicitly behind HTTPS (EUGENE_COOKIE_SECURE=true).
  const useSecure = process.env.EUGENE_COOKIE_SECURE === "true";
  store.set({
    name: "eugene_jwt",
    value: data.access_token,
    httpOnly: true,
    sameSite: "lax",
    path: "/",
    maxAge: data.expires_in,
    secure: useSecure,
  });
  return NextResponse.json({
    access_token: data.access_token,
    expires_in: data.expires_in,
  });
}
